import { defineStore } from "pinia";
import Local from "tools-utils/storage";
import { router } from "@/router";
/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore("userInfoStore", {
  state: () => ({
    token: "",
    userInfo: {},
    roles: [],
    auths: [],
  }),
  getters: {
    // 多个权限验证，满足一个则显示
    hasAuth: state => {
      return authKeys => {
        return Array.isArray(authKeys) && state.auths.some(key => authKeys.includes(key));
      };
    },
    // 多个权限验证，全部满足则显示
    hasAuthAll: state => {
      return authKeys => Array.isArray(authKeys) && authKeys.every(key => state.auths.includes(key));
    },
  },
  actions: {
    /** 内部：统一处理登录结果 */
    _consumeLoginResp(data = {}) {
      // 后端 data 里已经有 token，就直接用
      const token = data.token || "";

      // 1) 内存
      this.token = token;
      this.userInfo = data; //  不改动，完整保存后端返回

      // 2) 本地缓存
      Local.set("token", token);
      Local.set("userInfo", this.userInfo);
    },

    /** 密码登录 */
    async LoginByPwd(payload = {}) {
      const res = await Api.login.LoginByPwd({
        mobile: payload.mobile,
        pass: payload.password, // 按你接口的字段来
        code: payload.imgCode,
        cid: payload.captchaId,
      });
      const data = res.data || {};
      this._consumeLoginResp(data);
      return data;
    },

    /** 短信登录 */
    async LoginByCode(payload = {}) {
      const res = await Api.login.LoginByCode({
        mobile: payload.mobile,
        code: payload.smsCode,
      });
      const data = res.data || {};
      this._consumeLoginResp(data);
      return data;
    },

    // 获取权限点
    GetUserAuths() {
      return new Promise((resolve, reject) => {
        Api.user
          .GetUserAuths()
          .then(res => {
            const data = res.data || [];
            this.auths = data || [];
            // 存储 权限点 到浏览器缓存
            Local.set("user-auths", this.auths);
            resolve(res);
          })
          .catch(reject);
      });
    },

    // 直接清缓存并跳转登录
    Logout() {
      // 1) 清 pinia 状态（配合 persist 会同步覆盖本地持久化）
      if (typeof this.$reset === "function") {
        this.$reset();
      } else {
        this.token = "";
        this.userInfo = {};
        this.roles = [];
        this.auths = [];
      }

      // 2) 清除所有本地缓存（你们的 Local.clear 会清空 localStorage）
      try {
        Local.clear();
      } catch (e) {
        console.warn("[Logout] Local.clear error:", e);
        // 兜底：即使出错也继续跳转
      }

      // 3) 直接跳登录页（不带 redirect）
      router.replace("/login");
    },
  },
  persist: true, // 开启自动缓存
});
